#include "Subsystems/BlockBehaviors/SubsystemTorchBlockBehavior.h"
#include "Blocks/TorchBlock.h"
#include "Blocks/JackOLanternBlock.h"
#include "Subsystems/SubsystemTerrain.h"
#include "Managers/BlocksManager.h"

namespace PocketSurvival
{

    SubsystemTorchBlockBehavior::SubsystemTorchBlockBehavior()
    {
        m_handleBlocks.push_back(TorchBlock::Index());              // 火把
        m_handleBlocks.push_back(JackOLanternBlock::Index());       // 南瓜灯
    }

    void SubsystemTorchBlockBehavior::onNeighborBlockChanged(int32_t x, int32_t y, int32_t z, int32_t neighborX, int32_t neighborY, int32_t neighborZ)
    {
        int32_t cellValueFast = m_terrain->getCellValue(x, y, z);
        int32_t contents = Terrain::ExtractContents(cellValueFast);
        
        // 火把没有附着点的话，就应该被破坏
        if(contents == TorchBlock::Index())
        {
            Point3 point = CellFace::FaceToPoint3(Terrain::ExtractData(cellValueFast));
            int32_t x2 = x - point.posX;
            int32_t y2 = y - point.posY;
            int32_t z2 = z - point.posZ;
            int32_t cellContents2 = m_terrain->getCellContents(x2, y2, z2);
            if (GameSingleton::blocksManager->blocks[cellContents2]->IsCollidable == false)
            {
                m_terrain->destroyCell(0, x, y, z, 0, false);
            }
        }

        // 南瓜灯下方没有可碰撞的方块的话，就应该被破坏
        else if(contents == JackOLanternBlock::Index())
        {
            int32_t cellContents = m_terrain->getCellContents(x, y - 1, z);
            if (GameSingleton::blocksManager->blocks[cellContents]->IsCollidable == false)
            {
                m_terrain->destroyCell(0, x, y, z, 0, false);
            }
        }
    }

    static const std::string subsystemName = "TorchBlockBehavior";
    const std::string& SubsystemTorchBlockBehavior::getName() const
    {
        return subsystemName;
    }
    void SubsystemTorchBlockBehavior::load(const nlohmann::json& json)
    {
        m_terrain = GameSingleton::singletonPtr->getSingleton<SubsystemTerrain>();
    }
}